unit UPluginGroups;

interface

uses
  SysUtils, Classes, Contnrs, UPluginClasses;

type
  TPluginItem = class(TObject)
  private
    FPlugin: TPluginClass;
    FPluginName: string;
  public
    property Plugin: TPluginClass read FPlugin write FPlugin;
    property PluginName: string read FPluginName write FPluginName;
  end;

  TPluginGroup = class(TObject)
  private
    FObjectList: TObjectList;
    function GetItem(Index: Integer): TPluginItem;
    function GetItemCount: Integer;
  public
    constructor Create;
    destructor Destroy; overload;

    procedure AddItem(APluginClass: TPluginClass; APluginName: string);
    function FindItem(APluginName: string): TPluginClass;
    property Items[Index: Integer]: TPluginItem read GetItem;

    property ItemCount: Integer read GetItemCount;
  end;

function PluginGroup: TPluginGroup;
procedure RegisterPlugin(APluginClass: TPluginClass; APluginName: string);

implementation

var
  FPluginList: TPluginGroup = nil;

function PluginGroup: TPluginGroup;
begin
  if not Assigned(FPluginList) then
    FPluginList := TPluginGroup.Create;
  Result := FPluginList;
end;

procedure RegisterPlugin(APluginClass: TPluginClass; APluginName: string);
begin
  PluginGroup.AddItem(APluginClass, APluginName);
end;

{ TPluginGroup }

procedure TPluginGroup.AddItem(APluginClass: TPluginClass; APluginName: string);
var
  lPlugin: TPluginItem;
begin
  lPlugin := TPluginItem.Create;
  lPlugin.Plugin := APluginClass;
  lPlugin.PluginName := APluginName;
  FObjectList.Add(lPlugin);
end;

constructor TPluginGroup.Create;
begin
  FObjectList := TObjectList.Create;
  FObjectList.OwnsObjects := True;
end;

destructor TPluginGroup.Destroy;
begin
  FObjectList.Free;
end;

function TPluginGroup.FindItem(APluginName: string): TPluginClass;
var
  I: Integer;
begin
  for I := 0 to ItemCount - 1 do
  begin
    if Items[I].PluginName = APluginName then
    begin
      Result := Items[I].Plugin;
      Exit;
    end;
  end;
  Result := nil;
end;

function TPluginGroup.GetItemCount: Integer;
begin
  Result := FObjectList.Count;
end;

function TPluginGroup.GetItem(Index: Integer): TPluginItem;
begin
  Result := TPluginItem(FObjectList(Index));
end;

initialization

finalization
  FreeAndNil(FPluginList);

end.
